<?php

App::uses('AppController', 'Controller');

class ProizvodiController extends AppController {
	
	public $uses = array('Product', 'Client');
	public $paginate = array(
		'limit' => ITEMS_PER_PAGE
	);
	
	public function index() {
		$this->_setCommonData();
		
		$conditions = array();
		if(!empty($this->params->query)) {
			$filter = $this->params->query;
			$filter['name'] = trim($filter['name']);
			$this->set(compact('filter'));
			
			if($filter['name']) {
				$conditions['Product.name LIKE'] = '%' . $filter['name'] . '%';
			}
			if($filter['product_type']) {
				$conditions['Product.product_type_id'] = $filter['product_type'];
			}
		}
		
		$this->set("products", $this->paginate('Product', $conditions));
	}
	
	public function proizvod($id) {
	    $this->set('data', $this->Product->findById($id));
	    if($this->params['named']['ajax']) {
	        $this->layout = 'ajax';
	    }
	}
	
	private function _setCommonData() {
		$this->set("product_types", $this->Product->ProductType->find("list"));
		$this->set("clients", $this->Client->find("list"));
	}
	
	public function novi() {
		$this->_setCommonData();
		$this->set("product", $this->Product->create());
		$this->render("form");
	}
	
	public function izmeni($id) {
		$this->_setCommonData();
		$this->set("product", $this->Product->findById($id));
		$this->render("form");
	}
	
	public function sacuvaj() {
		if(!empty($this->data)) {
			$data = $this->data;
			$this->set("data", $data);
			
			if(floatval($data['ProductPrice'][-1]['price'])==0) {
				unset($data['ProductPrice'][-1]);
			}
			
			$this->Product->create($data);
			if($this->Product->validates()){
				$this->Product->ProductPrice->deleteAll(array("product_id"=>$this->Product->id));
				if($this->Product->saveAll($data)) {
					$this->setFlash("Proizvod je uspešno sačuvan.", "ok");
					$this->redirect('izmeni/'.$this->Product->id);
				}else{
					$this->_setCommonData();
					$this->set("product", $data);
					$this->setFlash("Čuvanje nije uspelo.");
					return $this->render("form");
				}
			}else{
				$this->_setCommonData();
				$this->set("product", $data);
				$this->setFlash("Uneti podaci nisu validni. Čuvanje nije uspelo.");
				return $this->render("form");
			}
		}
		$this->redirect("index");
	}
	
	public function obrisi($id) {
		if($this->Product->delete($id)) {
			$this->setFlash("Proizvod je obrisan.");
		}
		$this->redirect("index");
	}
}